library(ncdf)
library(gtools)
library(car)
#### working with multiple files ###############################################

## specify outpath for storage of renamed files
dirpath <- "C:/Users/Steffi/Documents/=Uni/Projektarbeit/MonatTRMM"
outpath <- "C:/Users/Steffi/Documents/=Uni/Projektarbeit/MonatTRMMOut"

## list all files in dirpath with that have '.nc' in their name
fnames <- list.files(dirpath, recursive = T, pattern = ".nc")

## extract long and short file names
##nchar zaehlt die Anzahl der Elemente des Vektors
fnames_long <- subset(fnames, nchar(fnames) == 20)
fnames_short <- subset(fnames, nchar(fnames) == 19)

## extract hour from short names and create long hour specifications
##substr gibt einen Teil des Vektors zur??ck
##paste verbindet Vektoren nachdem sie in characters umgewandelt worden sind
short_hour <- substr(fnames_short, 13, 13)
long_hour <- paste("0", short_hour, sep = "")
short_hour <- paste(".", short_hour, ".", sep = "") ##wofuer?
long_hour <- paste(".", long_hour, ".", sep = "")

## replace hour bit in short file names with long hour specification
##gsub ersetzt ein Textmuster durch eine Zeichenfolge im GESAMTEN Text
fnames_short <- lapply(1:length(fnames_short), function(i) {
  gsub(short_hour[i], long_hour[i], fnames_short[i], fixed = T)
}
                            )
## create new fnames_new list (with long hour specification)
fnames_new <- c(fnames_long, fnames_short)
fnames_new <- mixedsort(fnames_new) ## sort into proper temporal order
##mixedsort sortiert Strings in die richtige Reihenfolge

## now rename files on disk so they comply with new (longer) file names
file.copy(from = paste(dirpath, fnames, sep = "/"), 
          to = paste(outpath, fnames_new, sep = "/"))

## read in all files in 'names_list' - returns list with data frames
data_list <- lapply(1:length(fnames_new), function(i) {
  open.ncdf(paste(outpath, fnames_new[i], sep = "/"), write = F, readumlim = T)
  }
                    )

Prec <- lapply(1:length(data_list), function(i) {
  get.var.ncdf(data_list[[i]], varid = "precipitation")
  }
               )

##auf ein Listenelement zugreifen
#Prec[[2]]

##transposed
#PrecTran <- lapply(1:length(data_list), function(i) t(Prec[[i]]) )

## source TRMMDatCut function
source("C:/Users/Steffi/Documents/pa-prec-downscaling/TRMMDatCut_TIM.R")

## apply TRMMDatCut reursively over each list element (transposed)
Prec_cut_kili <- lapply(1:length(Prec), function(i) {
  cut_matrix(x = t(Prec[[i]]),
             Res = 0.25,
             LongMin = -180,
             LongMax = 180,
             LatMin = -50,
             LatMax = 50,
             cutLongMin = 37.25,
            cutLongMax = 37.5,
             cutLatMin = -3.5,
            cutLatMax = -3.25)
}
                        )

##load station data
station <- read.table("C:/Users/Steffi/Documents/=Uni/Projektarbeit/ki_0000cof3_000pu1_201104010000_201104302355_eat_ca01_nai05_0010.dat_suh03", sep = ",", header = T)

##change list to vector
Prec_cut_kili_vector <- unlist(Prec_cut_kili)

##plot station data ans satellite data with regressionline
xyplot(Prec_cut_kili_vector ~ station$precip_pu1, type = "p", 
       panel = function(x, y, ...){
  panel.xyplot(x, y, ...)
  panel.lmlineq(x, y, rot = T, at = 0.2, r.squared = T)
})

##get r squared
r?? <- str(summary(lm(lm(Prec_cut_kili_vector ~ station$precip_pu1)))$r.squared)